package controller

import (
	"net/http"
	"server_cluster/common/tools"
	"server_cluster/http/http_config"
	"server_cluster/http/service"
	"strconv"
	"time"

	"server_cluster/common/logger"

	"github.com/gin-gonic/gin"
)

type Controller struct {
	s *service.Service
}

// func (c *Controller) authorize() gin.HandlerFunc {
// 	return func(context *gin.Context) {
// 		token := context.GetHeader("token")
// 		uid, err := c.s.CheckGmAccountToken(token)
// 		if err == nil {
// 			// 验证通过
// 			context.Set("uid", uint64(uid))
// 			context.Set("token", token)
// 			context.Next()
// 			return
// 		}
// 		// 验证不通过
// 		context.Abort()
// 		context.JSON(http.StatusOK, GmTokenInvalid)
// 	}
// }

func Cors() gin.HandlerFunc {
	return func(context *gin.Context) {
		method := context.Request.Method
		context.Header("Access-Control-Allow-Origin", "*")
		context.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token, x-token")
		context.Header("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
		context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		context.Header("Access-Control-Allow-Credentials", "true")

		if method == "OPTIONS" {
			context.AbortWithStatus(http.StatusNoContent)
		}

		context.Next()
	}
}

func NewController(s *service.Service) (*Controller, error) {
	c := &Controller{
		s: s,
	}
	go func(addr string) {
		if logger.LOG.Level != logger.DEBUG {
			gin.SetMode(gin.ReleaseMode)
		} else {
			gin.SetMode(gin.DebugMode)
		}
		if !http_config.CONF.DevEnv {
			go c.backServer()
			go s.CalcTowerRank()
			s.SetServerStartTime()
		}
		gin.DefaultWriter = new(logger.LogWriter)
		gin.ForceConsoleColor()
		engine := gin.Default()
		engine.Use(Cors())
		engine.StaticFS("/client", http.Dir("./static/client"))
		engine.POST("/login", c.login)
		engine.GET("/gmInfo", c.gmInfo)
		engine.GET("/userinfo", c.userInfo)
		engine.PUT("/updateinfo", c.updateUserInfo)
		//engine.GET("/announcement", c.announcement)
		//engine.POST("/tower/rank", c.towerRank)
		// engine.POST("/api/account/sdk/login", c.accountSdkLogin)
		//engine.POST("/api/gm/account/login", c.gmAccountLogin)
		// engine.Use(c.authorize())
		// // 需要验证token的接口
		// engine.POST("/api/gm/account/reg", c.gmAccountReg)
		// engine.GET("/api/gm/account/info", c.gmAccountInfoGet)
		// engine.POST("/api/gm/account/info", c.gmAccountInfoUpdate)
		// engine.POST("/api/gm/account/password/change", c.gmAccountPasswordChange)
		// engine.POST("/api/gm/account/logout", c.gmAccountLogout)
		// engine.GET("/api/gm/server/config/stop/server", c.gmServerConfigStopServerGet)
		// engine.POST("/api/gm/server/config/stop/server", c.gmServerConfigStopServerSet)
		// engine.GET("/api/gm/server/config/ip/white", c.gmServerConfigIpWhiteGet)
		// engine.POST("/api/gm/server/config/ip/white/add", c.gmServerConfigIpWhiteAdd)
		// engine.POST("/api/gm/server/config/ip/white/del", c.gmServerConfigIpWhiteDel)
		// engine.GET("/api/gm/server/config/uid/white", c.gmServerConfigUidWhiteGet)
		// engine.POST("/api/gm/server/config/uid/white/add", c.gmServerConfigUidWhiteAdd)
		// engine.POST("/api/gm/server/config/uid/white/del", c.gmServerConfigUidWhiteDel)
		// engine.POST("/api/gm/server/cmd", c.gmServerCmd)

		//server := &http.Server{Addr: addr, Handler: engine}
		//ln, err := net.Listen("tcp4", addr)
		//if err != nil {
		//	panic(err)
		//}
		//type tcpKeepAliveListener struct {
		//	*net.TCPListener
		//}
		//err = server.Serve(tcpKeepAliveListener{ln.(*net.TCPListener)})
		err := engine.Run(addr)
		if err != nil {
			logger.Error("gin run error: %v", err)
			return
		}
	}(":" + strconv.Itoa(int(http_config.GetConfig().HttpPort)))
	return c, nil
}

func (c *Controller) backServer() {
	logger.Info("back server start...")
	for {
		if c.s.TimeNow <= tools.TimeNow() {
			// 60秒同步一次
			c.s.TimeNow = tools.TimeNow() + 60
			c.s.ServerList, _ = c.s.GetAllGateServer()
		}
		time.Sleep(1 * time.Second)
	}
}
